package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Configuration
public class GobalFilter implements GlobalFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //响应和请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取路径
        String path = request.getURI().getPath();
        //设置白名单
        if(path.contains("login")){
            //放行
            System.out.println("登录白名单:"+path);
            return chain.filter(exchange);
        }
        if(path.contains("addLogin")){
            System.out.println("注册白名单:"+path);
            return chain.filter(exchange);
        }
        //看看请求是否携带token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            System.out.println("请求token不存在:"+path);
            return response.setComplete();
        }
        //判断redis中的token是否过期
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer id = body.get("id", Integer.class);
        String tokenKey = "token-"+id;
        String s = redisTemplate.opsForValue().get(tokenKey);
        if(StringUtils.isEmpty(s)){
            System.out.println("缓存token过期:"+path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //判断token是否一致
        if(!s.equals(token)){
            System.out.println("token错误:"+path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //续期
        redisTemplate.expire(tokenKey,20, TimeUnit.MINUTES);
        return chain.filter(exchange);
    }
}
